﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.FileMatch
{
    public class FileCodeMatchItem
    {
        public Dictionary<string, string> FileNameToCode = new Dictionary<string, string>();
        public Dictionary<string, string> FileCodeToName = new Dictionary<string, string>();

        public string FullFileName { get; internal set; }
        public string LastReadFileTime { get; set; } = string.Empty;

        /// <summary>
        /// 文件名称，文档代码
        /// </summary>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        internal void Add(string v1, string v2,out string debuggerTxt)
        {
            if (FileNameToCode.ContainsKey(v1))
            {
                debuggerTxt = "FileNameToCode存在相同的Key" + v1;
                return;
            }
            if (FileCodeToName.ContainsKey(v2))
            {
                debuggerTxt = "FileCodeToName存在相同的Key" + v1;
                return;
            }
            debuggerTxt = null;
            FileNameToCode.Add(v1, v2);
            FileCodeToName.Add(v2, v1);
        }

        internal string GetByFileName(string code)
        {
            foreach (var key in FileNameToCode.Keys)
            {
                if (key.EndsWith(code))
                {
                    return FileNameToCode[key];
                }
            }
            return code;
        }
        internal string GetByFileCode(string fileCode,out string debuggerText)
        {
            debuggerText = "";
            if (FileCodeToName.ContainsKey(fileCode))
            {
                return FileCodeToName[fileCode];
            }
            
            if (FileCodeToName.Count == 0) {
                debuggerText = "空的FileCodeMatchItem,要找的fileCode是" + fileCode;
            }
            else
            {
                var key = FileCodeToName.Keys.ToList()[0];
                var value = FileCodeToName[FileCodeToName.Keys.ToList()[0]];
                var str = "已经存在的包括,key是" + key + ",value是" + value + ",要找的fileCode是" + fileCode + ",总数量是" + FileCodeToName.Count + ",上次更新时间是" + LastReadFileTime;
                debuggerText = str; 
            }
            return null;
        }
        internal void Clear()
        {
            this.FileCodeToName.Clear();
            this.FileNameToCode.Clear();
        }
    }

    public class FileCodeMatch
    {
        private static Dictionary<string, FileCodeMatchItem> m_fileCodeMatch = new Dictionary<string, FileCodeMatchItem>();
        private static int m_lastRetryLoadFileCodeMatch = 0;
        public static string GetFileCode(string code, string appName)
        {
            if (int.TryParse(code.Split('-')[0], out int t))
            {
                return code;
            }

            FileCodeMatchItem selItem = null;
            if (m_fileCodeMatch.ContainsKey(appName) == false)
            {
                selItem = new FileCodeMatchItem();
                m_fileCodeMatch.Add(appName, selItem);
            }
            else
            {
                selItem = m_fileCodeMatch[appName];
            }

            if (m_fileCodeMatch.Count == 0)
            {
                var fileName = Path.Combine(WSocketHandle.GetContendDir(appName), "fileMatch.txt");
                if (File.Exists(fileName) == false)
                {
                    return code;
                }

                var lines = File.ReadAllLines(fileName);
                for (var i = 0; i < lines.Length; i++)
                {
                    var kv = lines[i].Split(':');
                    selItem.Add(kv[0], kv[1],out string degbuggerValue);
                    if (degbuggerValue != null)
                    {
                        return null;
                    }
                }
            }
            return selItem.GetByFileName(code);

        }
        public static string GetFileName(string fileCode, string appName,out string degbuggerValue)
        {
            FileCodeMatchItem selItem = null;
            if (m_fileCodeMatch.ContainsKey(appName) == false)
            {
                selItem = new FileCodeMatchItem();
                m_fileCodeMatch.Add(appName, selItem);
            }
            else
            {
                selItem = m_fileCodeMatch[appName];
            }
            //File.WriteAllText("D:\\DE2.txt", (selItem.FileCodeToName.Count).ToString());
            if (selItem.FileCodeToName.Count == 0)
            {
                selItem.Clear();
                var fileName = Path.Combine(WSocketHandle.GetContendDir(appName), "fileMatch.txt");
                selItem.FullFileName = fileName;
                selItem.LastReadFileTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                if (File.Exists(fileName) == false)
                {
                    degbuggerValue = "fileMatch.txt不存在";
                    return null;
                }

                var lines = File.ReadAllLines(fileName);
                if(lines.Length == 0)
                {
                    degbuggerValue = "fileMatch.txt为空:"+ fileName;
                    return null;
                }

                for (var i = 0; i < lines.Length; i++)
                {
                    var t = lines[i].LastIndexOf(':');
                    var kv1 = lines[i].Substring(0,t);
                    var kv2= lines[i].Substring(t+1);
                    selItem.Add(kv1, kv2, out degbuggerValue);
                    if (degbuggerValue != null)
                    {
                        degbuggerValue += "这行=" + lines[i];
                        return null;
                    }
                }
            }
            var resValue= selItem.GetByFileCode(fileCode, out degbuggerValue);
            if (resValue == null)
            {
                //File.WriteAllText("D:\\DE1.txt", (System.Environment.TickCount - m_lastRetryLoadFileCodeMatch).ToString());
                if (Math.Abs(System.Environment.TickCount - m_lastRetryLoadFileCodeMatch) > 5000)
                {
                    m_lastRetryLoadFileCodeMatch= System.Environment.TickCount;
                    selItem.Clear();
                    return GetFileName(fileCode, appName, out degbuggerValue);
                }
            }
            return resValue;

        }
    }
}
